/**
 * 
 */
package com.jr.javachat.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.jr.javachat.listener.RemoteContentListener;

/**
 * NewUserService
 * 
 * 编写时间：2011-5-9下午02:50:50
 * @author <a href="http://xiulin.tk/">彭修林</a>
 * 
 */
public class NewUserService implements Runnable {

	private InputStream is;
	private DataInputStream in;
	private OutputStream os;
	private DataOutputStream out;
	private Server server;
	private String outString = "";

	public NewUserService(Socket newUser, Server server){
		try {
			this.server = server;
			is = newUser.getInputStream();
			in = new DataInputStream(is);
			os = newUser.getOutputStream();
			out = new DataOutputStream(os);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		//本进程获取服务端用户的输入值，然后通过outputStream发送给用户
		System.out.println("正在为用户提供服务 ...");

		RemoteContentListener listener = new RemoteContentListener(in);
		Thread t = new Thread(listener);
		t.start();
		String serverSays;
		while(true){
			try {
//这句话不合时机
System.out.println("正在向客户端发送消息");
					serverSays = server.getUserInput().toString();
					outString = (serverSays==null)?"Here is null !":serverSays;
//测试输出。
System.out.println("发送的内容是：【"+outString+"】");
					out.writeChars(outString);//读取用户输入，读取完成，发送至连接者

				//发送完以后，继续等待				

			} catch (IOException e) {
				e.printStackTrace();
			} catch(Exception e){
				System.err.println("您正在以不安全方式退出");
			}
		}

	}

}
